package com.fhz.shop.ui.mine;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.fhz.shop.R;
import com.fhz.shop.base.BaseFragment;
import com.fhz.shop.callback.ApiResponse;
import com.fhz.shop.cons.Cons;
import com.fhz.shop.databinding.FragmentHomeBinding;
import com.fhz.shop.databinding.FragmentMineBinding;
import com.fhz.shop.entity.HUser;
import com.fhz.shop.ui.home.HomeViewModel;
import com.fhz.shop.ui.login.ui.login.LoginActivity;
import com.fhz.shop.util.ImageLoader;
import com.fhz.shop.util.ImagePickerActivity;
import com.qiniu.android.common.FixedZone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.tencent.mmkv.MMKV;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import dagger.hilt.android.AndroidEntryPoint;


@AndroidEntryPoint
public class MineFragment extends BaseFragment<MineViewModel, FragmentMineBinding> {

    @Override
    protected void initData() {

        //判断有没有登录.没有调到登录界面
        //1 数据库
        //2 sp -mmkv
        MMKV mmkv = MMKV.defaultMMKV();
        HUser user = mmkv.decodeParcelable("user", HUser.class,null);
        if(user == null){
            //跳转
            LoginActivity.launch(getActivity());
        }


        binding.mineUserAvatar.setOnClickListener(v -> {
            //token .实际上,要从相册或者相机取到以后图片,把图片路径(公网可访问的),发给后端.
            //1,怎么打开,相册或者相机
              //原生
//            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//            startActivityForResult(intent, 11);

            //2,第三方选择器
            ImagePickerActivity.launch(getActivity());

        });



        binding.mainLogout.setOnClickListener(v -> {
            logout();
        });


    }

    @Override
    public void onResume() {
        super.onResume();
        MMKV mmkv = MMKV.defaultMMKV();
        HUser user = mmkv.decodeParcelable("user", HUser.class);
        ImageLoader.load(getActivity(),user.getHeadImage(),binding.mineUserAvatar);
    }

    private void logout() {
        MMKV mmkv = MMKV.defaultMMKV();
        mmkv.clear();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getFilePath(String path){
        //获取七牛token,并上传图片

        MMKV mmkv = MMKV.defaultMMKV();
        HUser user = mmkv.decodeParcelable("user", HUser.class);

        viewModel.getQiNiuToken().observe(this, stringApiResponse -> {
            String token = stringApiResponse.getData();
            Configuration config = new Configuration.Builder()
                    .zone(FixedZone.zone2)
                    .build();
            UploadManager uploadManager = new UploadManager(config);

            String key = String.valueOf(System.currentTimeMillis()).concat("_").concat(user.getNickname());

            uploadManager.put(path, key, token,
                    (key1, info, res) -> {
                        //res 包含 hash、key 等信息，具体字段取决于上传策略的设置
                        if(info.isOK()) {
                            Log.i("qiniu", "Upload Success");
                            String url = Cons.HTTP.concat(key);

                            viewModel.updateHeadImage(user.getNickname(), url).observe(this, stringApiResponse1 -> {
                                if(stringApiResponse1.code == 0){
                                    Toast.makeText(getActivity(), "更新成功!", Toast.LENGTH_SHORT).show();
                                    ImageLoader.load(getActivity(),url,binding.mineUserAvatar);
                                }
                                    Toast.makeText(getActivity(), "更新失败!", Toast.LENGTH_SHORT).show();
                            });

                            //发送器请求,需修改数据库中的图片地址
                        } else {
                            Log.i("qiniu", "Upload Fail");
                            //如果失败，这里可以把 info 信息上报自己的服务器，便于后面分析上传错误原因
                        }
                        Log.i("qiniu", key1 + ",\r\n " + info + ",\r\n " + res);
                    }, null);
        });
    }

    @Override
    public void onStart() {
        super.onStart();

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected MineViewModel createViewModel() {
        return new ViewModelProvider(this).get(MineViewModel.class);
    }
}